﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.ComponentModel;

namespace DiscoveryLogic.Analytics.UI.Common.PropGrid
{
	public class PropertyCollection : CompositeItem
	{
		#region Initialization

		public PropertyCollection() { }

		public PropertyCollection(object instance)
		{
			Dictionary<string, PropertyCategory> groups = new Dictionary<string, PropertyCategory>();
			PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(instance);
			List<Property> propertyCollection = new List<Property>();
			foreach (PropertyDescriptor propertyDescriptor in properties)
			{
				CollectProperties(instance, propertyDescriptor, propertyCollection);
			}
			foreach (Property property in propertyCollection)
			{
				PropertyCategory propertyCategory;
				if (groups.ContainsKey(property.Category))
				{
					propertyCategory = groups[property.Category];
				}
				else
				{
					propertyCategory = new PropertyCategory(property.Category);
					groups[property.Category] = propertyCategory;
					Items.Add(propertyCategory);
				}
				propertyCategory.Items.Add(property);
			}
		}

		private void CollectProperties(object instance, PropertyDescriptor descriptor, List<Property> propertyCollection)
		{
			if (descriptor.Attributes[typeof(FlatAttribute)] == null)
			{
				Property property = new Property(instance, descriptor);
				if (descriptor.IsBrowsable)
				{
					propertyCollection.Add(property);
				}
			}
			else
			{
				instance = descriptor.GetValue(instance);
				PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(instance);
				foreach (PropertyDescriptor propertyDescriptor in properties)
				{
					CollectProperties(instance, propertyDescriptor, propertyCollection);
				}
			}
		}

		#endregion
	}
}
